<?php
/**
 * Geneone: Content Management Framework
 * Object Namespace Search
 *
 * @package Geneone
 * @author Khlo
 * @version 1.0
 * @copyright 2004-2006 Geneone Development Team
 */
 
require_once ('Gene/Search.php');
require_once ('Gene/Search/Result/Object.php');
 
class Gene_Search_Source_Object {
	/**
	 * Runs a search using the specified phrase and options.
	 *
	 * @var string $phrase Search Phrase
	 * @var array $options Specific Search Options
	 *
	 * @return object Gene_Search_Result object. PEAR_Error on failure.
	 */
	function &getSearch($phrase, $options=array()) {
		$db =& Gene::getDatabase();
		
		if (!isset($options['require_all'])) {
			$options['require_all'] = true;
		}
		
		$terms = array_keys(Gene_Search::getTerms($phrase));
		
		if (!count($terms)) {
			$result = PEAR::raiseError("No search terms provided.");
		} else if (count($terms) > 10) {
			$result = PEAR::raiseError("Too many search terms provided.");
		} else {
			foreach ($terms as $j => $k) {
				$terms[$j] = $db->quote($k);
			}
			
			if (count($terms) > 1 && $options['require_all']) {
				$having = "HAVING terms=".count($terms)." ";
			} else {
				$having = "";
			}
			
			$q = $db->query ("SELECT o.*, COUNT(s.term) AS terms, SUM(s.weight) AS weight FROM ".Gene::tableName("object_search_index")." s LEFT JOIN ".Gene::tableName("objects")." o ON (s.object_id=o.object_id) WHERE s.term IN (".implode(",", $terms).") GROUP BY s.object_id ".$having."ORDER BY weight DESC, o.t_create DESC");
			
			$result = new Gene_Search_Result_Object($q, $phrase);
		}
		
		return $result;
	}
}
 
?>